<!DOCTYPE html>
<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>简单聊天室</title>
<script type="text/javascript">
	var webSocket = null;
	if ("WebSocket" in window) {
		// 创建WebSocket对象
		webSocket = new WebSocket("ws://192.168.43.137:8088/chat");
	} else {
		alert("您的浏览器不支持 WebSocket!");
	}

	
	var sendMsg = function() {
		var inputElement = document.getElementById('msg');
		if (inputElement.value == '')
			alert("输入内容不为空");
		else {
			if (inputElement.value == "quit" || inputElement.value == "exit") {
				webSocket.close();
				return;
			}
			
			// 发送消息
			webSocket.send(inputElement.value);
			// 清空单行文本框
			inputElement.value = "";
		}
	}
	var send = function(event) {
		if (event.keyCode == 13) {
			sendMsg();
		}
	};
	
	webSocket.onopen = function() {
		n = prompt('请给自己取一个昵称：');
		if (n != '')
			webSocket.send(n);
		else
			//设置游客登录
			webSocket.send("游客" + Math.random() * 100000000000000000);
		
		// 此处可以加一个异步请求name是否使用的请求来判断name是否可用
		
		document.getElementById('msg').onkeydown = send;
		document.getElementById('sendBn').onclick = sendMsg;
	};
	
	// 为onmessage事件绑定监听器，接收消息
	webSocket.onmessage = function(event) {
		var show = document.getElementById('show')
		// 接收、并显示消息
		show.innerHTML += new Date() + "<br/>" + event.data + "<br/>";
		//让聊天框滚动条始终显示新消息
		show.scrollTop = show.scrollHeight;
	};
	
	webSocket.onclose = function() {
		document.getElementById('msg').onkeydown = null;
		document.getElementById('sendBn').onclick = null;
	};
</script>
</head>
<body>
	<div style="width: 600px; height: 240px; overflow-y: auto; border: 1px solid #333;" id="show"></div>
	<input type="text" size="80" id="msg" name="msg" placeholder="输入聊天内容" />
	<input type="button" value="发送" id="sendBn" name="sendBn" />
</body>
</html>